/* components*/
import InitiateDialog from 'src/modules/task/view/components/TaskCustomNodes/InitiateDialog.vue'
/* api*/
import {
    getTaskCustomNodeFields,
    saveCustomNode,
    getCurrentNodeExecutorAndNodeHandlingPerson,
    getSelectNodeCompleteTime,
    checkNeedVipApprove,
    getCurrentDraftCustomerNode
} from '@src/api/TaskApi'
/* enum*/
import TaskStateProcessEnum from '@model/enum/TaskStateProcessEnum.ts'
/* utils*/
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'
import { isEmpty } from 'pub-bbx-utils'
import {isConnectorCard} from "@service/CardService";
import { getRootWindow } from '@src/util/dom';


// 工单当前状态和节点的映射关系
const flowMapState = {
    created: ['allot'],  // 待指派-指派
    taskPool: ['accept'], // 工单池-接受
    allocated: ['accept'], // 已指派-接受
    accepted: ['start'], // 已接受-开始（如果开始没有，对应下一个自定义）
    processing: ['finish'], // 进行中-（如果有自定义，对应下一个自定义，否则对应完成）
    finished: ['cost'], // 已完成
}
export default {
    name: 'task-custom-node-mixin',
    data() {
        return {
            addonsRequird: [], // 工单必填的附加组件
            nodeHandledPersons: [], // 办理过节点的人员
            flowNodeStatus: [], // 进度条
            flowNodeTimes: [], // 存储自定义节点的时间
            processCurrentState: this.initData?.task?.state ?? '',
            customStateName: '',// 已经走过的自定义节点的状态
        }
    },
    components: {
        [InitiateDialog.name]: InitiateDialog,
    },
    computed: {
        // 工单节点拓展灰度
        taskFlowExtend() {
            const RootWindow = getRootWindow(window);
            return RootWindow?.grayAuth?.[GrayFunctionEnum.TaskFlowExtend] ?? false // 工单流程节点灰度
        },
        // 当前节点的id，可能为空(已取消状态不取currentNodeId，此时应该为空，后端不好处理，前端加下判断)
        currentNodeId() {
            return this.task?.state !== 'offed' ? this.task?.attribute?.currentNodeId ?? '' : ''
        },
        /*
       * 自定义节点的信息（根据工单信息存储的自定义节点的id去查询）
       * nodeBtnName:按钮名称
       * nodeStateName：节点状态
       * nodeResponsiblePerson:节点负责人
       * */
        customNode() {
            const node = this.taskALlNode?.find(item => item.id === this.currentNodeId) ?? {}
            return {...node, ...node?.data}
        },
        /*当前自定义节点的title:高级审批显示*/
        customNodeTitle() {
            return this.customNodeBtnShow ? this.customNode?.title : ''
        },
        /*当前自定义节点的title:高级审批显示*/
        customNodeId() {
            return this.customNodeBtnShow ? (this.customNode?.id ?? '') : ''
        },
        /*是否到了自定义节点阶段
        条件1：当前节点为自定义节点(自定义节点的信息)
        * */
        customNodeBtnShow() {
            return !isEmpty(this.customNode) && this.customNode?.type === 'normal'
        },
        /*是否显示自定义节点按钮
        条件1：非审批状态
        条件2：非暂停状态
        条件3：当前节点为自定义节点(自定义节点的信息)
        条件4：当前登录人为节点负责人(包括工单负责人)
        * */
        isCanCustomNode() {
            return !this.isApproving && !this.isPaused && this.customNodeBtnShow && this.isCustomExecutor
        },
        /* 该登录账户是否是节点负责人 */
        isCustomExecutor() {
            const currentNodeExecutorIds = this.task?.currentNodeExecutor?.map(item => item.userId)
            return currentNodeExecutorIds?.includes(this.loginUser.userId);
        },
        // 附加组件当前节点对应的value
        currentNodeBtnKeys() {
            return this.customNodeBtnShow ? [this.customNode?.id] : (flowMapState?.[this.task?.state] ?? [])
        },
        customNodeUserName() {
            return this.customNodeBtnShow ? `${this.customNode.title}${this.$t('task.executor')}` : ''
        },
        // 是否显示多个附加组件按钮
        showMoreAddonsBtn() {
            return this.addonsRequird?.length > 1;
        },
        // 是否一个附加组件按钮
        showOneAddonsBtn() {
            return this.addonsRequird?.length === 1;
        },
        // 附加组件
        sigleAddon() {
            return this.addonsRequird?.[0] ?? {}
        },
        // 是否可以修改节点负责人（1.节点负责人，2。系统管理员）
        allowModifyCustomExecutor() {
            return this.isCustomExecutor || this.loginUser?.roles?.some(item => item == 1)
        }
    },
    methods: {
        // 获取进度条
        async getTaskProgress() {
            try {
                const { result } = await getSelectNodeCompleteTime({ taskId: this.task.id })

                this.flowNodeStatus = []

                for(const key in result) {
                    if(TaskStateProcessEnum[key]) {
                        this.flowNodeStatus.push(TaskStateProcessEnum[key])
                    }else {
                        const name = this.taskALlNode?.find(item => item.id === key)?.data?.nodeStateName ?? ''
                        // 存储自定义节点节点
                        name && this.flowNodeStatus.push({
                            name,
                            value: key
                        })
                        // 存储自定义节点开始的时间
                        this.flowNodeTimes.push({
                            key,
                            time: result?.[key] ?? ''
                        })
                    }
                }
            }  catch (e) {
                console.error(e)
            }
        },

        // 获取当前工单所有节点信息
        async getTaskFlowNode() {
            if(!this.taskFlowExtend) return;
            try {
                // 工单流程进度条当前显示值，因为自定义节点的state都是'procsing'，需要取当前所在节点的上一个自定义节点的id
                let previousNode = {}; // 获取上个完成的节点
                this.taskALlNode?.forEach((item, index) => {
                    if(this.task.state !== 'offed' && item.id === this.task?.attribute?.currentNodeId && index > 0) {
                        previousNode = this.taskALlNode[index - 1]
                    }
                })
                if(this.taskFlowExtend && previousNode && previousNode?.type === 'normal') {
                    this.processCurrentState = previousNode?.id ?? ''
                    this.customStateName = previousNode?.data?.nodeStateName ?? ''
                }

            } catch (e) {
                console.error(e)
            }finally {
                await this.getTaskProgress()
            }
        },

        // 获取工单当前节点的负责人
        async getCurrentNodeExecutor() {
            try {
                this.nodeHandledPersons = []
                const { result, success } = await getCurrentNodeExecutorAndNodeHandlingPerson({ taskId: this.task.id })

                if(!success) return;

                const { currentNodeExecutor} = result

                this.$set(this.task, 'currentNodeExecutor', currentNodeExecutor ?? [])

                // 改版-从task详情获取
                const nodeHandlingPerson = this.task?.attribute?.nodeHandlingPerson ?? {}
                const nodeHandlingPersonKeys = Object.keys(nodeHandlingPerson)
                // 已经办理过的节点办理人
                let customsFields = []
                // 需要排序节点负责人，所以用taskALlNode去循环
                this.taskALlNode?.forEach((item, index) => {
                    if(nodeHandlingPersonKeys.includes(item.id)) {
                        // 查询当前节点的节点名称
                        const nodeUserName = item.title ??''
                        customsFields.push({
                            displayName: `${nodeUserName}${this.$t('common.form.preview.stock.sparepartStockDisplayName.approveName')}`,
                            fieldName: item.id,
                            formType: 'user',
                            isSystem: 1,
                        })
                        this.$set(this.task, item.id, nodeHandlingPerson[item.id])
                    }
                })
                // 当前节点负责人
                if(this.customNodeUserName) {
                    customsFields.push({
                        displayName: this.customNodeUserName,
                        fieldName: 'currentNodeExecutor',
                        formType: 'user',
                        isSystem: 1,
                    })
                }
                const index = this.fields?.findIndex(item => item.fieldName === 'completeTime')
                index > 0 && this.fields.splice(index, 0, ...customsFields)
            } catch (e) {
                console.error(e)
            }
        },

        // 打开自定义节点弹框
        async openCustomNode({ startNode = false } = {}) {
            try {
                this.pending = true;
                const { success, result, message } = await getTaskCustomNodeFields({ taskId: this.task.id });

                if(!success) return await this.$message.error(message)

                const fields = result?.filter(item => item.isHidden == 0) ?? []

                if(startNode) {
                    return fields;
                }else {
                    // 无表单直接完成节点
                    if(!fields?.length) return await this.submitCustomerNode();

                    // 获取暂存的字段值
                    const { result = {} } = await getCurrentDraftCustomerNode({ taskId:this.task.id, currentNodeId: this.currentNodeId })
                    const temporaryStorageVal = result?.formData ?? {}

                    // 打开编辑自定义节点的表单
                    this.$refs.InitiateDialogRef?.openCustomNodeDialog(fields, this.customNode.title, this.task, temporaryStorageVal);
                }

            } catch (e) {
                console.error(e)
            } finally {
                this.pending = false;
            }
        },

        /*校验自定义节点是否有开启了高级审批*/
        async checkCustomNodeVipApprove(params) {
            let needVipApprove = false
            try {
                const { success, result, message } = await checkNeedVipApprove({
                    nodeFormData: {},
                    taskId: this.task.id,
                    action: 'nodeTask',
                    nodeTaskBizId: this.currentNodeId,
                });

                if(!success) {
                    this.$message.error(message)
                    throw new Error(message)
                }
                needVipApprove = result?.needVipApprove ?? false

                // 需要高级审批
                if (success && result?.needVipApprove) {
                    this.proposeApprove(result ?? {})
                }
            }  catch (e) {
                throw new Error(e)
            }
            return needVipApprove;
        },
        // 节点完成
        async submitCustomerNode() {
            try {
                const params = {
                    taskId: this.task.id,
                    formData: {},
                    currentNodeId: this.currentNodeId,
                }

                // 完成节点前校验高级审批
                if(await this.checkCustomNodeVipApprove(params)) return ;

                const { success, message} = await saveCustomNode(params)
                if(!success) return this.$message.error(message);

                window.location.href = `${this.$resourcePrefix}/task/view/${this.task.id}`;
            } catch (e) {
                console.error(e)
            }
        },

        // 开始节点
        async beforeStart() {
           try {
               const fields = await this.openCustomNode({startNode: true})
               if(fields?.length) {
                   // 获取暂存的字段值
                   const { result = {} } = await getCurrentDraftCustomerNode({ taskId:this.task.id, currentNodeId: 'start' })
                   const temporaryStorageVal = result?.formData ?? {}
                   this.$refs.InitiateDialogRef?.openCustomNodeDialog(fields, this.$t('common.base.start'), this.task, temporaryStorageVal, true);
               }else {
                   this.start();
               }
           } catch (e) {
               console.error(e)
           }
        },

        // 默认打开附加组件
        async openAddonsDialogAuto(res) {
            if(res.message) {
                await this.$alert(res.message)
            }
            if(!this.taskFlowExtend) return;
            const cardId =  res.data
            // 切换到需要填写的附加组件
            const tab = this.taskLayoutTabBarList?.find(item => item.cardId === cardId)

            // 不是当前tab再切换
            if(tab && tab?.tabName !== this.rightActiveTab) {
                this.tabBarChangeItem(tab)
            }
            this.$nextTick(() => {
                // 判断当前附加组件是否是故障清单
                if(tab?.tabName === 'fault-tab') {
                    this.rightActiveTab = tab.tabName;
                    this.$refs.faultTabRef?.openFaultDialogAuto();
                }else {
                    // 打开附加组件的弹框
                    this.$refs.taskDetailCard?.openAddonsDialog(this.taskCards?.find(item => item.cardId === cardId))
                }
            })
        },

        // 获取必填的附加组件
        getAddonsBtn() {
            // 获取系统设置配置的当前节点必填的附加组件
            let addons = this.initData?.taskType?.cardSetting?.cardInfo?.filter(item => item.notNullFlow && this.currentNodeBtnKeys.includes(item.notNullFlow)) ?? []

            // 判断权限
            this.addonsRequird = addons?.filter(item => {
                const card = this.initData?.cardInfo?.find(zitem => zitem.cardId === item.id)

                let { canWrite, canRead, canCreate, canDelete } = card;
                const isHaveAuth = (canWrite || canRead || canCreate || canDelete)
                const isHaveFields = card.fields.length

                // 是否为连接器附加组件，连接器附加组件里面不存字段列表，所以只判断权限就可以
                if ((isConnectorCard(card) && isHaveAuth) || (isHaveAuth && isHaveFields)) {
                    return item
                }
            })?.map(item => {
                return {
                    cardId: item.id,
                    btnName: this.$t('common.base.addModule', {module: item?.cardNameLanguage?.[this.$i18n.locale] ?? item.name }) // 按钮名称翻译
                }
            })
        },
        handleCommandAddBtn(cardId) {
            this.openAddonsDialogAuto({data: cardId})
        },
    },
    watch: {
        // 节点负责人（是否是节点负责人更新-按钮权限也需要更新）
        isCustomExecutor: {
            handler(val) {
                const customNode = this.stateButtonData?.find(item => item.isCustomBtn)
                customNode && (customNode.show = val);
            }
        }
    },
}